package com.spaceraccoons.server;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketServlet;

/**
 * Simple echo service
 * @author Benjamin P. Jung
 */
public class EchoServlet extends WebSocketServlet {

	/** @see java.io.Serializable */
	private static final long serialVersionUID = -5554810215709991738L;

	@Override
	public WebSocket doWebSocketConnect(HttpServletRequest req, String resp) {
		return new EchoSocket();
	}

	public class EchoSocket implements WebSocket.OnTextMessage {

		private Connection connection;

		@Override
		public void onOpen(Connection connection) {
			this.connection = connection;
		}

		@Override
		public void onClose(int closeCode, String message) {
			this.connection = null;
		}

		@Override
		public void onMessage(final String data) {
			System.out.println("<< " + data);
			try {
				connection.sendMessage(data);
				System.out.println(">> " + data);
			} catch (IOException e) {
				// TODO Handle exception
				e.printStackTrace();
			}
		}

	}

}